package com.feng.rabbitmq.config;

import org.springframework.amqp.core.*;
import com.rabbitmq.client.impl.AMQImpl;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class DelayedQueueConfig {
    //队列
    public static final String DELAYED_QUEUE_NAME = "delayed.queue";
    //交换机
    public static final String DELAYED_EXCHANGE_NAME = "delayed.exchange";
    //toutingKey
    public static final String DELAYED_ROUTING_KEY = "delayed.routingkey";

    /**
     * Caused by: com.rabbitmq.client.ShutdownSignalException: channel error;
     * protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_
     * FOUND - no queue 'delayed.queue' in vhost '/', class-id=50, method-id=10)
     * @return
     * no queue 'delayed.queue' in vhost '/'
     */
    //声明队列
    @Bean("delayedQueue")
    public Queue delayedQueue(){
//        return new Queue(DELAYED_QUEUE_NAME);
        return QueueBuilder.durable(DELAYED_QUEUE_NAME).build();
    }

    //声明交换机 自定义
    @Bean("delayedExchange")
    public CustomExchange delayedExchange(){
        Map<String,Object> arguments = new HashMap<>();
        arguments.put("x-delayed-type","direct");
        /**
         * 1. 交换机名称
         * 2. 交换机类型
         * 3. 是否持久化
         * 4. 是否需要自动删除
         * 5. 其他的参数
         */
        //no queue 'delayed.queue' in vhost
//        return new CustomExchange(DELAYED_EXCHANGE_NAME,"x-delayed-type",true,false,arguments);
        return new CustomExchange(DELAYED_EXCHANGE_NAME,"x-delayed-message",true,false,arguments);
    }

    //绑定队列和交换机
    @Bean
    public Binding delayedQueueExchange(@Qualifier("delayedQueue")Queue delayedQueue,
                                        @Qualifier("delayedExchange")CustomExchange delayedExchange){
        return BindingBuilder.bind(delayedQueue).to(delayedExchange).with(DELAYED_ROUTING_KEY).noargs();
    }
}
